package com.jay.net.clazz.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

class TCPClient implements Runnable {
	Socket socket;
	private String hostname;
	private int port;
	private String msg;

	public TCPClient(String hostname, int port) {
		this.hostname = hostname;
		this.port = port;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public void run() {
		try {
			socket = new Socket(hostname, port);
			OutputStream out = socket.getOutputStream();
			out.write(msg.getBytes());
			// write request, not shown …
			out.flush();
			InputStream in = socket.getInputStream();
			byte[] buffer = new byte[8192];
			while ((in.read(buffer)) >= 0) {

				System.out.println(new String(buffer));
			}
			// get reply …
		} catch (IOException e) { /* … */
		} finally
		// ensure socket is closed
		{
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e) {
			}
		} // end finally
	} // end run()
} // end class
